package com.bruce.pattern.creational.singleton;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 饿汉式单例模式
 * <p>
 * Created by bruce on 2018/11/3 0:48
 */
@Slf4j
public class HungrySingleton implements Serializable {

    private final static HungrySingleton hungrySingleton = new HungrySingleton();

    private HungrySingleton() {
        //防止反射攻击,这种方式仅仅适用于在class加载时创建实例的单例
        if (hungrySingleton != null){
            throw new RuntimeException("单例构造器禁止反射");
        }
        log.info("HungrySingleton is create");
    }

    public static HungrySingleton getInstance() {
        return hungrySingleton;
    }

    //该方法名固定,防止序列化,反序列化导致单例对象被改变
    //其实在ObjectInputStream反序列化会会判断是否有该方法,有的话则会被反射调用
    private Object readResolve(){
        return hungrySingleton;
    }


}
